package utils

import (
	"errors"
	"github.com/golang-jwt/jwt/v4"
	"storeManageApi/models/authModels"
	"time"
)

func (utils UtilService) CreateJWT(auth authModels.UserAuth) (string, error) {
	var JwtUser authModels.JwtUserAuth = authModels.JwtUserAuth{
		UserAuth: auth,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(utils.outTime * time.Second)),
			IssuedAt:  jwt.NewNumericDate(time.Now())},
	}
	var tokenOBJ *jwt.Token = jwt.NewWithClaims(jwt.SigningMethodHS256, JwtUser)
	var token string
	var JWTerr error
	token, JWTerr = tokenOBJ.SignedString(utils.signSecretKey)
	if JWTerr != nil {
		return "", JWTerr
	}
	return token, nil
}
func (utils UtilService) ParseToken(token string) (authModels.JwtUserAuth, error) {
	var JwtUser authModels.JwtUserAuth = authModels.JwtUserAuth{}
	key := utils.signSecretKey
	result, err := jwt.ParseWithClaims(token, &JwtUser, func(token *jwt.Token) (interface{}, error) {
		return key, nil
	})
	if err != nil {
		err = errors.New("token Parse Error")
		return authModels.JwtUserAuth{}, err
	}
	if !result.Valid {
		err = errors.New("token已过期")
		return authModels.JwtUserAuth{}, err
	}
	return JwtUser, err
}
